const fs = require('fs');
const path = require('path');
const os = require('os');

const fileName = process.argv[2];
const rawPathObj = path.parse(fileName);
const inputFilePath = path.resolve(rawPathObj.dir ? rawPathObj.dir : __dirname, fileName);
const inputPathObj = path.parse(inputFilePath);
const outputFilePath = path.resolve(inputPathObj.dir, `${inputPathObj.name}.hack`);

class LittleIO {
  constructor() {
    this.cache = [];
    this.inputLines = [];
  }

  hasMoreLines() {
    return this.inputLines.length > 0;
  }

  advance() {
    while (this.hasMoreLines() && this.isInvalidLine()) {
      this.dropOneline();
    }
    return this.dropOneline();
  }

  dropOneline() {
    const line = this.inputLines.shift();
    return line && line.split('//').shift().trim();
  }

  isInvalidLine() {
    const line = this.inputLines[0].trim();
    return line.trim() === '' || line.startsWith('//');
  }

  loadFile() {
    const input = fs.readFileSync(inputFilePath, { encoding: 'utf-8' });
    this.inputLines = String(input).split(os.EOL);
    this.cache = [];
  }

  writeToCache(line) {
    this.cache.push(line);
  }

  writeToFile() {
    const output = this.cache.join(os.EOL);
    fs.writeFileSync(outputFilePath, output + os.EOL);
  }
}

module.exports.LittleIO = LittleIO;
